#include "ota_memchunk.h"
#include <stdlib.h>
#include <string.h>

int ota_memchunk_init(MemChunk *chunk)
{
    // 约定好，chunk首次初始化必须要清零
    ota_memchunk_free(chunk);

    chunk->data = malloc(1);
    if (!chunk->data)
    {
        return -1;
    }

    chunk->size = 0;
    chunk->data[0] = 0;
    return 0;
}

int ota_memchunk_append(MemChunk *chunk, void *data, int size)
{
    char *temp = realloc(chunk->data, chunk->size + size + 1);
    if (!temp)
    {
        return -1;
    }

    chunk->data = temp;
    memcpy(chunk->data + chunk->size, data, size);
    chunk->size += size;
    chunk->data[chunk->size] = 0;
    
    return 0;
}

void ota_memchunk_free(MemChunk *chunk)
{
    if (chunk->data)
    {
        free(chunk->data);
        chunk->data = NULL;
    }
    chunk->size = 0;
}
